use std::fs::{File, OpenOptions};
use std::io::{self, BufRead, BufReader, BufWriter, Write};
use std::path::Path;

pub fn read_file<T>(path: &str, callback: T) -> io::Result<()>
where
    T: Fn(String) -> (),
{
    // let file = File::create(path).unwrap();
    let file = File::open(path)?;
    let reader = BufReader::new(file);
    for line in reader.lines() {
        callback(line?);
    }
    Ok(())
}

pub fn read_file1<T>(path: &str, callback: T)
where
    T: Fn(String) -> (),
{
    // let file = File::create(path).unwrap();
    match File::open(path) {
        Ok(file) => {
            let reader = BufReader::new(file);
            for line in reader.lines() {
                match line {
                    Ok(l) => {
                        // println!("显示文件内容：{}", l);
                        callback(l);
                    }
                    Err(_e) => {}
                }
            }
        }
        Err(_e) => {}
    }
}

/**
 * 写入文件，如果文件不存在就新建一个文件
 * path 文件地址
 * content 写入内容
 * if_append 是否在后面追加
 */
pub fn write_file_byte(path: &str, content: &[u8], if_append: bool) -> io::Result<()> {
    let option_file = OpenOptions::new()
        .write(true)
        .append(if_append)
        .create(true)
        .open(path)?;

    let mut writer: BufWriter<File> = BufWriter::new(option_file);
    writer.write_all(content)?;
    writer.flush()?;

    return Ok(());
}

/**
 * 写入文件，如果文件不存在就新建一个文件
 * path 文件地址
 * content 写入内容
 * if_append 是否在后面追加
 */
pub fn write_file(path: &str, content: &str, if_append: bool) -> io::Result<()> {
    write_file_byte(path, content.as_bytes(), if_append)?;
    return Ok(());
}

/**
 * 写入文件，如果文件不存在就新建一个文件
 * path 文件地址
 * content 写入内容
 */
pub fn write_file_append(path: &str, content: &str) -> io::Result<()> {
    write_file_byte(path, content.as_bytes(), true)?;
    return Ok(());
}

/**
 * 读取地址中的全部文件
 */
pub fn read_all_file(path: &str) -> io::Result<Vec<String>> {
    return read_all_file_path(Path::new(path))
}

/**
 * 读取文件夹中的全部文件
 */
pub fn read_all_file_path
(path: &Path) -> io::Result<Vec<String>> {
    for entity in std::fs::read_dir(path)? {
        let entity = entity?;
        let path: std::path::PathBuf = entity.path();
        if entity.file_type()?.is_dir() {
            read_all_file_path(path.as_path())?;
            continue;
        }
        println!("显示地址内容：{:?}", path.file_name());
    }

    return Ok(vec![String::from("")]);
}